#!/usr/bin/env bash
help()
{
  echo "名称：encode"
  echo "介绍：一个可以直接转换文件编码的极简命令，集判断与转换为一体，具有文件编码自动判断，误判率较小，不是没有，大多数够用"
  echo
  echo "这里建议保留原文件"
  echo "用法：encode <文件名> <转换编码>"
  echo "或"
  echo "encode [options] <file>"
  echo "[options]："
  echo "    -help  查看帮助"
  echo "    -v <file>  查看文件的详细信息"
}

size()
{
  filesize=$(stat -c $"%s" "$1")
  dw="B"
  if ((filesize >= 1024));then
    filesize=$((filesize/1024))
    dw="KB"
  fi
  if ((filesize >= 1024));then
    filesize=$((filesize/1024))
    dw="MB"
  fi
  if ((filesize >= 1024));then
    filesize=$((filesize/1024))
    dw="GB"
  fi
  if ((filesize >= 1024));then
    filesize=$((filesize/1024))
    dw="TB"
  fi
  echo "大    小: ${filesize}${dw}"
}

if [[ $# == 0 ]];then
  help
  exit 0
fi

option_type="none"
if [[ "$1" =~ ^-.* ]];then
  option_type="options"
else
  if [[ -x "$1" ]];then
    filetype="x"
  elif [[ -f "$1" ]];then
    filetype="f"
  else
    echo "${1}: error: 不是文件或者文件不存在"
    exit 1
  fi
  if (( $# < 2 ));then
    echo "error: 没有输入编码类型"
    exit 2
  fi
  encoding=$(uchardet "$1")
  iconv -f ${encoding} -t "$2" "$1" >> "${1}.temp" 2>/dev/null 
  if [[ $? != 0 ]];then
    echo "error: 没有这种编码类型"
    rm -rf "${1}.temp"
    exit 3
  fi
  read -p "是否保存原文件 Y/N" filetemp
  filetemp=${filetemp: -y}
  if [[ $filetemp == "N" || $filetemp == "n" ]];then
    rm -rf $1
    mv "${1}.temp" "${1}"
    if [[ $filetype == "x" ]];then
      chmod +x "${1}"
    fi
    echo "编码转换成功"
  else
    roots=$(echo "$1" | grep -o ".*/")
    filename=$(echo "$1" | awk -F/ '{print $NF}')
    encod_file="${roots}${2}_${filename}"
    for ((i=0;;i++));do
      if [[ -e "$encod_file" ]];then
        encod_file="${roots}${2}${i}_${filename}"
      else
        break
      fi
    done
    mv "${1}.temp" "$encod_file"
    if [[ $filetype == "x" ]];then
      chmod +x "$encod_file"
    fi
    echo "编码转换成功"
  fi
fi

if [[ $option_type == "options" ]];then
  case $1 in
    -help)
      help
      ;;
    -v)
      if (( $# < 2 ));then
        echo "error: 没有输入文件名"
        exit 5
      fi
      if [[ -f "$2" ]];then
        filename=$(echo "$2" | awk -F/ '{print $NF}')
        echo "文件名称：${filename}"
        size "$2"
        stat -c $"权    限: %F" "$2"
        echo "编    码: $(uchardet $2)"
        stat -c $"修改时间: %y" "$2"
      else
        echo "${2} : 该文件不存在或者是目录"
        exit 1
      fi
      ;;
    *)
      echo "error: 没有这个参数，输入 encode -help 查看帮助"
      exit 4
  esac
fi
